package priv.mill.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.mill.controller.util.RetenObj;
import priv.mill.entry.Comments;
import priv.mill.server.CommentsService;

@Controller
@RequestMapping("Comments")
public class CommentsController {

	@Autowired
	private CommentsService commentsService;

	private static final Logger logger = Logger.getLogger(CommentsController.class);

	@RequestMapping("getCommentsById")
	@ResponseBody
	public RetenObj getCommentsById(@RequestParam("CommentsId") Integer commentsId) {
		try {
			return warpData(commentsService.getCommentsById(commentsId), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	private RetenObj warpData(Object object, int i) {
		RetenObj retenObj = new RetenObj();
		retenObj.setData(object);
		retenObj.setStatus(i);
		return retenObj;
	}

	@RequestMapping("getCommentsByEntry")
	@ResponseBody
	public RetenObj getCommentsByEntry(Comments comments) {
		try {
			return warpData(commentsService.getCommentsByEntry(comments), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("getCommentssByPage")
	@ResponseBody
	public RetenObj getCommentssByPage(Comments comments) {
		try {
			return warpData(commentsService.getCommentssByPage(comments), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("updateComments")
	@ResponseBody
	public RetenObj updateComments(Comments comments) {
		try {
			int result = commentsService.updateComments(comments);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}
	

	@RequestMapping("insertComments")
	@ResponseBody
	public RetenObj insertComments(Comments comments) {
		try {
			int result = commentsService.insertComments(comments);
			if (result > 0)
				return warpData(comments.getCmId(), 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("deleteComments")
	
	@ResponseBody
	public RetenObj deleteComments(Integer commentsId) {
		try {
			int result = commentsService.deleteComments(commentsId);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}

	}
}
